<script setup lang="ts">
import { nextTick, onMounted, Ref, ref, watch } from 'vue'
import {
  IconSearch,
  IconUpload,
  IconDownload,
  IconDelete,
  IconEye,
  IconRefresh
} from '@arco-design/web-vue/es/icon'
import { useFilePreview } from '@/composables/useFilePreview'
import FilePreview from '@/components/attaches/FilePreview.vue'
import { useUserStore, useTeamStore } from '@/store/index'
import {
  addAttacheUsingPost,
  deleteAttacheUsingDelete,
  pageAttachesUsingPost
} from '@/api/attacheController'
import { Message, Modal } from '@arco-design/web-vue'
import { Table, TableColumn, Space, Button, Avatar, Tag } from '@arco-design/web-vue'
import { formatFileSize, downloadFile } from '@/utils/file'
import dayjs from 'dayjs'
import { pageProjectUsingPost } from '@/api/projectController'
const userStore = useUserStore()
const teamStore = useTeamStore()

//上传附件
// 附件上传请求参数
const addAttacheRequest = ref<API.AddAttacheRequest>({
  type: 0, // 团队类型
  typeId: teamStore.selectedTeam?.id, // 团队ID
  fileName: undefined
})
// 处理文件上传前的验证
const beforeUpload = (file: File) => {
  const maxSize = 10 * 1024 * 1024 // 10MB
  console.log(file.size)
  if (file.size > maxSize) {
    Message.error('文件大小不能超过10MB')
    return false
  }

  // 设置文件名
  addAttacheRequest.value.fileName = file.name
  return true
}

// 处理文件上传
const handleUpload = async (option: any) => {
  const { fileItem } = option

  try {
    // 构建上传参数
    addAttacheRequest.value.fileName = fileItem.file.name
    addAttacheRequest.value.typeId = teamStore.selectedTeam?.id
    // 上传文件
    const res: any = await addAttacheUsingPost(addAttacheRequest.value, fileItem.file)

    if (res.code === 0) {
      Message.success('上传成功')
      // 刷新文件列表
      await getAttaches(true)
    } else {
      Message.error(res.message || '上传失败')
    }
  } catch (error) {
    Message.error('文件上传失败 ' + error)
  }
}

// 搜索条件
const searchForm = ref({
  name: '',
  type: 0, // 团队文档
  typeId: teamStore.selectedTeam?.id
})
//搜索方法
const doSearch = async () => {
  await nextTick()
  pageAttacheRequest.value.name = searchForm.value.name
  pageAttacheRequest.value.type = searchForm.value.type
  pageAttacheRequest.value.typeId = searchForm.value.typeId
  await getAttaches(true)
}
// 监听 typeId 的变化
watch(
  () => searchForm.value.typeId,
  (newVal) => {
    // 根据选中选项的 type 字段判断文档类型
    const selectedOption = searchOptions.value.find((option) => option.value === newVal)
    if (selectedOption) {
      searchForm.value.type = selectedOption.type === 'team' ? 0 : 1 // team -> 0, project -> 1
      searchForm.value.typeId = selectedOption.value
    }
  }
)

// 添加分页相关变量
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
})

// 文档列表
const Attaches: Ref<API.AttachesVo[]> = ref([])
const pageAttacheRequest = ref<API.PageAttacheRequest>({
  current: 1,
  pageSize: 10,
  name: '',
  type: 0,
  typeId: teamStore.selectedTeam?.id
})

// 获取文档列表
const getAttaches = async (reset: boolean = false) => {
  try {
    if (reset) {
      pageAttacheRequest.value.current = 1
    }
    const res: any = await pageAttachesUsingPost(pageAttacheRequest.value)
    Attaches.value = res.data.records
    // 更新分页信息
    pagination.value.current = Number(res.data.current)
    pagination.value.total = Number(res.data.total)
    pagination.value.pageSize = Number(res.data.size)
  } catch (error) {
    console.error(error)
  }
}

// 处理页码变化
const handlePageChange = async (page: number) => {
  pageAttacheRequest.value.current = page
  await getAttaches()
}

// 处理每页条数变化
const handlePageSizeChange = async (pageSize: number) => {
  pageAttacheRequest.value.current = 1 // 切换每页条数时重置为第一页
  pageAttacheRequest.value.pageSize = pageSize
  await getAttaches()
}

// 重置方法
const handleReset = async () => {
  searchForm.value = {
    name: '',
    type: 0, // 默认为团队文档
    typeId: teamStore.selectedTeam?.id
  }
  // 重置请求参数
  pageAttacheRequest.value = {
    current: 1,
    pageSize: 10,
    name: '',
    type: 0, // 默认为团队文档
    typeId: teamStore.selectedTeam?.id
  }
  // 重新加载数据
  await getAttaches(true)
}

//删除文件
// 处理文件删除
const deleteAttacheRequest: Ref<API.DeleteAttacheRequest> = ref({
  type: searchForm.value.type,
  typeId: searchForm.value.typeId,
  attacheId: undefined
})

const handleDeleteAttache = async (attache: any) => {
  // 添加确认框
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除附件 "${attache.name}" 吗？`,
    okText: '确认删除',
    cancelText: '取消',
    onOk: async () => {
      try {
        deleteAttacheRequest.value.typeId = searchForm.value.typeId
        deleteAttacheRequest.value.attacheId = attache.id
        const res: any = await deleteAttacheUsingDelete(deleteAttacheRequest.value)
        if (res.code === 0) {
          Message.success('删除成功')
          Attaches.value = Attaches.value.filter((attacheVo: any) => attacheVo.id !== attache.id)
        } else {
          Message.error(res.message || '删除失败')
        }
      } catch (e) {
        Message.error('删除失败 ' + e)
      }
    }
  })
}
// 文件预览相关
const { previewVisible, previewFile, handlePreview, closePreview, getFileIcon } = useFilePreview()

// 处理下载
const handleDownload = (record: any) => {
  // 实现下载逻辑
  console.log('下载文件:', record)
}
// 搜索选项数据
const searchOptions = ref([
  {
    label: '团队文档',
    value: teamStore.selectedTeam?.id,
    type: 'team' // 标识为团队文档
  }
])
//#region 我的项目
const projects: Ref<API.ProjectVo[]> = ref([])
// 查询我的项目参数
const pageProjectRequest: Ref<API.PageProjectRequest> = ref({
  current: 1,
  pageSize: 1000,
  teamId: teamStore?.selectedTeam?.id,
  title: '',
  code: undefined,
  ownerId: undefined
})
// 加载我的项目列表
const loadProjects = async () => {
  try {
    const res: any = await pageProjectUsingPost(pageProjectRequest.value)
    if (res.code === 0) {
      projects.value = res.data.records || []
      // 项目追加到搜索选项中，添加 type 字段标识为项目文档
      searchOptions.value.push(
        ...projects.value.map((project: any) => ({
          label: project.title,
          value: project.id,
          type: 'project' // 标识为项目文档
        }))
      )
    } else {
      Message.error(res.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('Failed to load projects:', error)
    Message.error('获取项目列表失败')
  }
}
//#endregion
// 获取文档列表
onMounted(async () => {
  await getAttaches()
  await loadProjects()
})

// 添加判断是否可以删除文件的方法
const canDelete = (record: API.AttachesVo) => {
  // 如果是团队文档，只有团队管理员可以删除
  if (searchForm.value.type === 0) {
    return teamStore.selectedTeam?.ownerId === userStore.user?.id
  }
  // 如果是项目文档，在查询时已经做了权限过滤，直接返回 true
  return true
}
</script>

<template>
  <div class="docs-center">
    <a-space :size="16" direction="vertical" fill>
      <!-- 添加页面标题 -->
      <div class="page-title">
        <h2>文档中心</h2>
      </div>

      <!-- 搜索条件区域 -->
      <a-card>
        <div class="search-area">
          <div class="search-inputs">
            <a-input-search
              v-model="searchForm.name"
              placeholder="请输入文件名搜索"
              search-button
              @search="doSearch"
              @press-enter="doSearch"
            >
              <template #button-icon>
                <icon-search />
              </template>
            </a-input-search>

            <a-select
              v-model="searchForm.typeId"
              placeholder="选择项目"
              :options="searchOptions"
              @change="doSearch"
            />
          </div>

          <div class="action-buttons">
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>

            <div class="upload-wrapper">
              <a-upload
                :custom-request="handleUpload"
                :show-file-list="false"
                @before-upload="beforeUpload"
              >
                <template #upload-button>
                  <a-button type="primary">
                    <template #icon>
                      <icon-upload />
                    </template>
                    上传文件
                  </a-button>
                </template>
              </a-upload>
              <span class="upload-tip">文件大小 ≤ 10MB</span>
            </div>
          </div>
        </div>
      </a-card>

      <!-- 文件表格 -->
      <a-card>
        <a-table
          :data="Attaches"
          :pagination="{
            ...pagination,
            onChange: handlePageChange,
            onPageSizeChange: handlePageSizeChange
          }"
          :scroll="{ x: 1080 }"
        >
          <template #columns>
            <a-table-column title="文件名" data-index="name" :width="250">
              <template #cell="{ record }">
                <a-space>
                  <component :is="getFileIcon(record.name)" />
                  <span>{{ record.name }}</span>
                </a-space>
              </template>
            </a-table-column>

            <a-table-column title="扩展名" data-index="extension" :width="60" align="center">
              <template #cell="{ record }">
                <Tag>{{ record.name?.split('.').pop()?.toUpperCase() || '-' }}</Tag>
              </template>
            </a-table-column>

            <a-table-column title="大小" data-index="size" :width="60" align="center">
              <template #cell="{ record }">
                <span>{{ formatFileSize(record.size) }}</span>
              </template>
            </a-table-column>

            <a-table-column title="上传人" data-index="uploader" :width="120" align="center">
              <template #cell="{ record }">
                <a-space>
                  <a-avatar :size="24" :image-url="record.uploader.avatar">
                    {{ record.uploader.name?.[0] }}
                  </a-avatar>
                  <span>{{ record.uploader.name }}</span>
                </a-space>
              </template>
            </a-table-column>

            <a-table-column title="上传时间" data-index="createAt" :width="120" align="center">
              <template #cell="{ record }">
                <span>{{ dayjs(record.createAt).format('YYYY-MM-DD HH:mm:ss') }}</span>
              </template>
            </a-table-column>

            <a-table-column title="操作" :width="180" fixed="right" align="center">
              <template #cell="{ record }">
                <a-space>
                  <a-button type="text" @click="handlePreview(record)">
                    <template #icon><icon-eye /></template>
                    预览
                  </a-button>
                  <a-button type="text" @click="downloadFile(record)">
                    <template #icon><icon-download /></template>
                    下载
                  </a-button>
                  <a-button 
                    v-if="canDelete(record)"
                    type="text" 
                    status="danger" 
                    @click="handleDeleteAttache(record)"
                  >
                    <template #icon><icon-delete /></template>
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-card>
    </a-space>

    <!-- 文件预览组件 -->
    <FilePreview v-model:isPreviewOpen="previewVisible" :file="previewFile" @close="closePreview" />
  </div>
</template>

<style scoped>
.docs-center {
  padding: 16px;
  height: 100%;
}

.button-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.upload-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-tip {
  color: var(--color-text-3);
  font-size: 13px;
}

/* 搜索区域样式 */
.search-area {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.search-inputs {
  display: flex;
  gap: 16px;
  flex: 1;
  min-width: 300px;
}

.search-inputs :deep(.arco-input-search) {
  flex: 2;
  min-width: 200px;
}

.search-inputs :deep(.arco-select) {
  flex: 1;
  min-width: 150px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: nowrap;
}

.upload-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.upload-tip {
  color: var(--color-text-3);
  font-size: 13px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .search-area {
    gap: 12px;
  }

  .search-inputs {
    flex-direction: column;
    width: 100%;
    gap: 12px;
  }

  .search-inputs :deep(.arco-input-search),
  .search-inputs :deep(.arco-select) {
    width: 100%;
  }

  .action-buttons {
    width: 100%;
    justify-content: flex-end;
  }
}

@media screen and (max-width: 480px) {
  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .upload-wrapper {
    flex-direction: column;
    align-items: stretch;
  }

  .upload-tip {
    text-align: center;
  }
}

/* 添加页面标题样式 */
.page-title {
  margin-bottom: 4px;
}

.page-title h2 {
  font-size: 20px;
  font-weight: 500;
  color: var(--color-text-1);
  margin: 0;
  line-height: 32px;
}

/* 移除其他样式，使用 Arco Design 的内置样式 */
</style>
